package com.example.myapplication.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;

import com.example.myapplication.bean.User;
import com.example.myapplication.R;
import com.example.myapplication.utils.CodeUtils;
import com.example.myapplication.utils.SharedPreferencesUtil;
import com.google.gson.JsonObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.OkHttpClient;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;

import org.json.JSONException;
import org.json.JSONObject;

public class activity_login extends AppCompatActivity {

    private TextView tv_main_title;//标题
    private Button tv_back;		//返回按钮
    private TextView tv_register,tv_find_pwd;//立即注册、找回密码的控件
    private Button btn_login;	//登录按钮
    private RelativeLayout rl_title_bar;//标题布局
    private EditText et_user_name,et_pwd;//用户名、密码的控件
    private String username,pwd,spPwd;//用户名、密码的控件的获取值
    private CheckBox cb_box;
    //验证码
    private ImageView iv_showCode;
    private EditText et_phoneCode;
    //产生的验证码
    private String realCode;
    private List<User> userList = new ArrayList<>();
    private SharedPreferencesUtil su;
    OkHttpClient client = new OkHttpClient();
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private String picture;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //去除默认标题栏
        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }

        //设置此界面为竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        init();
        //验证码
        reacode();

        //        MODE_NIGHT_AUTO自动确定白天夜间模式
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.getDefaultNightMode());
    }

    //验证码
    private void reacode() {

        //将验证码用图片的形式显示出来
        iv_showCode.setImageBitmap(CodeUtils.getInstance().createBitmap());
        realCode =CodeUtils.getInstance().getCode();
    }
    private void init() {
        // TODO Auto-generated method stub
        tv_main_title = (TextView) findViewById(R.id.tv_main_title);
        tv_main_title.setText("登录");
        tv_back = ((Button) findViewById(R.id.tv_back));
        tv_register = (TextView) findViewById(R.id.tv_register);
        tv_find_pwd = (TextView) findViewById(R.id.tv_find_pwd);
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        su = SharedPreferencesUtil.getInstance(getApplicationContext());
        btn_login = (Button) findViewById(R.id.btn_login);
        et_user_name = (EditText) findViewById(R.id.et_user_name);
//        rl_title_bar = (RelativeLayout) findViewById(R.id.title_bar);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        cb_box = (CheckBox) findViewById(R.id.cb_box);
//        rl_title_bar.setBackgroundColor(Color.parseColor("#30b4ff"));
        //验证码
        et_phoneCode = (EditText) findViewById(R.id.et_phoneCodes);
        iv_showCode = (ImageView) findViewById(R.id.iv_showCode);
        boolean isremember = pref.getBoolean("cb_box", false);
        if (isremember) {
            //将账号和密码全部设置到文本框中
            String phone = pref.getString("phone", "");
            String password = pref.getString("password", "");
            et_user_name.setText(phone);
            et_pwd.setText(password);
            cb_box.setChecked(true);
        }

        //图片验证码刷新
        iv_showCode.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                iv_showCode.setImageBitmap(CodeUtils.getInstance().createBitmap());
                realCode = CodeUtils.getInstance().getCode();
            }
        });
        //返回按钮的点击事件
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                activity_login.this.finish();
            }
        });
        //立即注册控件的点击事件
        tv_register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(activity_login.this, activity_register.class);
                startActivityForResult(intent, 1);
            }
        });
        //找回密码点击事件
        tv_find_pwd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //跳转到找回密码界面（此界面暂时未创建）
                Intent intent = new Intent(activity_login.this, FindPswActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        //登录按钮点击事件
        btn_login.setOnClickListener(new View.OnClickListener() {

            String regEx = "(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,20}$";
            Pattern pattern = Pattern.compile(regEx);
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                username = et_user_name.getText().toString().trim();
                pwd = et_pwd.getText().toString().trim();
                Matcher matcher = pattern.matcher(pwd);
                if(matcher.matches()){
                    OkHttpUtils
                            .get()
                            .url("http://121.36.92.128:8086/login")
                            .addParams("userId", username)
                            .addParams("password", pwd)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int i) {
                                    System.out.println(e.toString());
                                }

                                @Override
                                public void onResponse(String response, int i) {

//                                if(response.equals("true"))
//                                    Toast.makeText(MainActivity.this, "登录成功！", Toast.LENGTH_LONG).show();
//                                else
//                                    Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_LONG).show();
                                    if (TextUtils.isEmpty(username)) {
                                        Toast.makeText(activity_login.this, "请输入用户名", Toast.LENGTH_SHORT).show();
                                        return;
                                    } else if (TextUtils.isEmpty(pwd)) {
                                        Toast.makeText(activity_login.this, "请输入密码", Toast.LENGTH_SHORT).show();
                                        return;
                                    } else if (!response.isEmpty()) {
                                        String phoneCode = et_phoneCode.getText().toString();
                                        if (phoneCode.equals(realCode)) {
                                            Toast.makeText(activity_login.this, "登录成功", Toast.LENGTH_SHORT).show();
                                            //把登录状态和登录的用户名保存到SharedPreferences里面
                                            //  System.out.println("...............................................");
                                            byOkHttp(username);
                                            //登录成功后通过Intent把登录成功的状态传递到MainActivity.java中
                                            Intent data = new Intent();
                                            data.putExtra("status", true);
                                            setResult(RESULT_OK, data);//setResult为OK，关闭当前页面

                                            try {
                                                JSONObject jsonObject = new JSONObject(response);
                                                picture = jsonObject.getString("picture");
                                            } catch (JSONException e) {
                                                throw new RuntimeException(e);
                                            }
                                            saveLoginStatus(true,username);
                                            //登陆后跳转
                                            Intent intent=new Intent(activity_login.this,ManageActivity.class);
                                            startActivity(intent);
                                            editor = pref.edit();
                                            if (cb_box.isChecked()) {
                                                editor.putBoolean("cb_box", true);
                                                editor.putString("phone", username);
                                                editor.putString("password", pwd);
                                            } else {
                                                editor.clear();
                                            }
                                            editor.apply();
                                        } else {
                                            Toast.makeText(activity_login.this, phoneCode + "验证码错误", Toast.LENGTH_SHORT).show();
                                        }
                                        return;
                                    } else if (!byOkHttpUtils(username) && !response.equals("true")) {
                                        Toast.makeText(activity_login.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                                        return;
                                    } else {
                                        Toast.makeText(activity_login.this, "此用户不存在", Toast.LENGTH_SHORT).show();
                                    }
                                }


                            });

                    // String md5Pwd=MD5Utils.MD5(pwd);
                    // spPwd=readPwd(username);


                    }else{
                    Toast.makeText(activity_login.this, "密码必须同时包含数字与字母,且长度为 6-20位", Toast.LENGTH_SHORT).show();
                }
                }

            public Boolean byOkHttpUtils(String userId){
                final Boolean[] flag = {false};
                OkHttpUtils
                        .get()
                        .addParams("userId",userId)
                        // .addParams("userName",userName)
                        //  .addParams("password",password)
                        .url("http://121.36.92.128:8086/register")
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int i) {

                            }

                            @Override
                            public void onResponse(String response, int i) {

                                if (response.equals("true")) {
                                    flag[0] = true;
                                    //Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_LONG).show();}
                                    // else
                                    //Toast.makeText(RegisterActivity.this, "注册失败，可能已存在当前账号", Toast.LENGTH_LONG).show();

                                }
//
                                // return response.equals("true");
                                //return return_value.equals("true")


                            }

                        });

                return flag[0];
            }
            public void byOkHttp(String userId){
                //创建OkHttpClient对象
                OkHttpUtils
                        .get()
                        .url("http://121.36.92.128:8086/update")
                        .addParams("userId", userId)
                        // .addParams("status", String.valueOf(status))
                        .build();

                if(userId!=null){
                    //从注册界面传递过来的用户名
                    //String username=data.getStringExtra("username");
                    System.out.println(true);
                    if(!TextUtils.isEmpty(username)){
                        et_user_name.setText(username);
                        //设置光标的位置上
                        et_user_name.setSelection(username.length());
                    }
                }
                //获取返回的json数据
                //String return_value = response.body().toString();
//                if(return_value.equals("true")){
//                    Toast.makeText(register.this, "注册成功！", Toast.LENGTH_LONG).show();
//                }
//                else {
//                    Toast.makeText(register.this, "注册失败，可能已存在当前账号邮箱", Toast.LENGTH_LONG).show();
//                }
                // return return_value.equals("true");
            }
            //从SharedPreferences中根据用户名读取密码
//    private String readPwd(String username){
//        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
//        return sp.getString(username,"");
//    }

            //保存登录状态和登录用户名到SharedPrefarences中
            private void saveLoginStatus(boolean status,String username){
                //loginInfo表示文件名
                SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
                SharedPreferences.Editor editor=sp.edit();//获取编辑器
                editor.putBoolean("isLogin", status);
                editor.putString("loginUserName", username);//存入登录时的用户名
                editor.putString("picture",picture);//存入登录人的头像url
                editor.commit();//提交修改
            }
//    @Override
//    protected void onActivityResult(int requestCode,int resultCode,
//                                    Intent data){
//        super.onActivityResult(requestCode, resultCode, data);
//        if(data!=null){
//            //从注册界面传递过来的用户名
//            String username=data.getStringExtra("username");
//            if(!TextUtils.isEmpty(username)){
//                et_user_name.setText(username);
//                //设置光标的位置上
//                et_user_name.setSelection(username.length());
//            }
//            }
//   }
        });
    }
}